package news.util;
import java.sql.*;

/**
 * @author Administrator
 * 数据库连接关闭工具类
 */
public class BaseDao {
    public Connection conn;
    public Statement st;
    public ResultSet rs;
    public PreparedStatement ps;


    /**
     * 建立sql连接
     */
    public void openDB(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/news?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","root");
            System.out.println("数据库连接成功！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 关闭sql连接
     */
    public void closeDB(){
        try {
            if (rs!=null){
                rs.close();
            }
            if (st!=null){
                st.close();
            }
            if (ps!=null){
                ps.close();
            }
            if (conn!=null){
                conn.close();
            }
            System.out.println("数据库已关闭！");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        BaseDao baseDao = new BaseDao();

        try {
            baseDao.openDB();
            String sql = "select * from news_topic";
            baseDao.st = baseDao.conn.createStatement();
            baseDao.rs = baseDao.st.executeQuery(sql);

            while (baseDao.rs.next()){
                System.out.println(baseDao.rs.getString("topicname")+"time:"+baseDao.rs.getDate("createtime"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            baseDao.closeDB();
        }
    }


}
